package com.hnx.admin.system.servce.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hnx.admin.api.security.core.SecurityPropertyAPI;
import com.hnx.admin.common.exception.UserEmptyException;
import com.hnx.admin.common.security.utils.RequestContextHolderUtil;
import com.hnx.admin.system.convert.user.UserConvert;
import com.hnx.admin.system.dao.user.UserDAO;
import com.hnx.admin.system.dto.user.UserDTO;
import com.hnx.admin.system.vo.user.UserDetailVO;
import com.hnx.admin.system.vo.user.UserVO;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Optional;

/*
创建人： 倔强的头发
创建时间：2024/7/7
功能描述:

*/
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService, SecurityPropertyAPI {
    private final UserDAO userDAO;
    private final UserConvert userConvert;
    @Override
//    @VerifyFunc
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<UserDTO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(USERNAME, username);
        UserDTO userDTO = userDAO.selectOne(queryWrapper);
        Optional.ofNullable(userDTO).orElseThrow(()->new UserEmptyException(USER_EMPTY));
        Map<String, Object> context = RequestContextHolderUtil.getContext();
        context.put("admin",userDTO.getSuperAdmin().getCode());
        UserVO userVO = userConvert.toUserVO(userDTO);
        return new UserDetailVO(userVO,userDTO.getPassword());
    }
}
